package com.dc.aimc.common.service.aop;

import com.dc.aimc.common.mybatis.context.TenantContext;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Log4j2
@Aspect
@Order(1)
@Component
public class TenantAspect {

    /**
     * 切换租户
     * 方法切入点要求: 任意返回类型 com.dc.aimc.所有包.controller.所有类.所有方法(所有参数)
     */
    @Before("execution(* com.dc.aimc.*.controller.*.*(..))")
    public void changeTenant() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            // 获取tenantId
            HttpServletRequest request = attributes.getRequest();
            String tenantId = request.getHeader("tenant-id");
            if (StringUtils.isNotBlank(tenantId)) {
                TenantContext.setTenantId(tenantId);
                log.info("切换到 {} 租户", tenantId);
            } else {
                log.error("租户信息异常: {}", tenantId);
            }
        } else {
            log.error("ServletRequestAttributes为空");
        }
    }

}
